﻿#include "VolcEngineRTCSubsystem.h"

#include "bytertc_video.h"
#include "bytertc_room.h"
#include "bytertc_room_event_handler.h"
#include "bytertc_video_event_handler.h"
DEFINE_LOG_CATEGORY(VRTCLog)

void UVolcEngineRTCSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);
}

void UVolcEngineRTCSubsystem::Deinitialize()
{
	Super::Deinitialize();

	if (m_room)
	{
		m_room->leaveRoom();
		m_room->destroy();
		m_room = nullptr;
	}
	
	if (m_video)
	{
		bytertc::destroyRTCVideo();
		m_video = nullptr;
	}
}

void UVolcEngineRTCSubsystem::InitVolcEngine(const FString& RoomID, const FString& UID, const FString& APPID, const FString& TOKEN)
{
	if (RoomID.IsEmpty() || TOKEN.IsEmpty() || UID.IsEmpty() || APPID.IsEmpty())
	{
		UE_LOG(VRTCLog, Error, TEXT("paras is empty"));
		return;
	}
	
	m_video = bytertc::createRTCVideo(TCHAR_TO_UTF8(*APPID), this, nullptr);
	
	if (m_video == nullptr)
	{
		UE_LOG(VRTCLog, Error, TEXT("m_video Invalid."));
		return;
	}
	
	m_video->startAudioCapture();
	m_room = m_video->createRTCRoom(TCHAR_TO_UTF8(*RoomID));
	
	if (m_room == nullptr)
	{
		UE_LOG(VRTCLog, Error, TEXT("m_room Invalid."));
		return;
	}
	
	bytertc::UserInfo uinfo;
	bytertc::RTCRoomConfig conf;
	uinfo.extra_info = nullptr;
	uinfo.uid = TCHAR_TO_UTF8(*UID);
	conf.is_auto_publish = true;
	conf.is_auto_subscribe_audio = true;
	conf.is_auto_subscribe_video = true;
	
	m_room->joinRoom(TCHAR_TO_UTF8(*TOKEN), uinfo, conf);
	m_room->setRTCRoomEventHandler(this);
}

void UVolcEngineRTCSubsystem::onRoomStateChanged(const char* room_id, const char* uid, int state, const char* extra_info)
{
	OnRoomStateChanged.Broadcast(room_id, uid, state, extra_info);
}

void UVolcEngineRTCSubsystem::onRoomMessageReceived(const char* uid, const char* message)
{
	OnRoomMessageReceived.Broadcast(uid, message);
}
